﻿using System;
using System.Linq;
using System.Data;

using DevExpress.XtraCharts.Web;
using DevExpress.Web.ASPxPager;
using System.Collections.Generic;
using olierFrm.DataBase.FrameWork.StdQuery;
using olierFrm.WebFormDev;
using olierFrm.WebFormDev.StdQuery;
using olierFrm.DataBase;
using olierFrm.Extensions.EDataTable;
using DevExpress.XtraCharts;

namespace WebFormDev.StdQueryPack
{
    public partial class ChartPage : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            
            ManageSystem.IsLogin();
            ManageSystem.SetTheme(Page);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (StdQuery.QueryName == null) { return; }
            if (!IsPostBack)
                loadGrid();
        }


        private void loadGrid()
        {
            DataTable dtSource = null;
            Dictionary<string, string> ParamMatch = new Dictionary<string, string>();
            if (Request.QueryString["MasterQueryName"] != null)
            {
                var dbMasterStdQuery = new StdQuerySQL(Request.QueryString["MasterQueryName"]);
                var script = olierFrm.DataBase.FrameWork.Plugin.SmartINI.LoadIni(dbMasterStdQuery.StdQuery.HintQuerys);
                var masterQuery = script.Where(s => s.Value["HintQueryName"].ToString() == StdQuery.QueryName);
                if (masterQuery.Count() == 1)
                {
                    var mqPM = masterQuery.First();
                    if (mqPM.Value["ParamMatch"].Trim().Length != 0)
                    {
                        var mqPMS = mqPM.Value["ParamMatch"].Split(';').ToList();
                        mqPMS.Remove("");
                        foreach (var m in mqPMS)
                        {
                            var kv = m.Split('=');
                            ParamMatch.Add(kv[0], kv[1]);
                        }
                    }
                }
            }

            var dbStdQuery = new StdQuerySQL(StdQuery.QueryName);
            foreach (var p in dbStdQuery.StdQueryParams)
            {
                if (ParamMatch.ContainsKey(p.ParamName))
                {
                    dbStdQuery.SetParam(p.ParamName, Request.QueryString[ParamMatch[p.ParamName]]);
                }
                else
                    dbStdQuery.SetParam(p.ParamName, Request.QueryString[p.ParamName]);

            }
            dbStdQuery.AddSystemParams();
            dtSource = dbStdQuery.ExecuteSQL();
            dtSource.BindCaptionToDataTable();
            dtSource.AddDataRowIndex();
            //数据字典
            //ASPxPager paperChart = new ASPxPager();
            //form1.Attributes.Add("style", "display:none");
            //paperChart.Summary.Text = "共{1}页，第{0}页（共{2}项）";
            //paperChart.PageIndexChanged += new EventHandler(paperChart_PageIndexChanged);

            //WebChartControl chartControl = new WebChartControl();
            //this.form1.Controls.Add(chartControl);
            //this.form1.Controls.Add(paperChart);
            BindChartControl(dbStdQuery, chartControl, paperChart, paperChart.PageIndex, Server.UrlDecode(Request.QueryString["ChartText"]), dtSource);
        }

        protected void paperChart_PageIndexChanged(object sender, EventArgs e)
        {
            loadGrid();
        }

        private void BindChartControl(StdQuerySQL dbStdQuery, WebChartControl chartControl, ASPxPager paper, int pageIndex, string text, DataTable dtSource)
        {
            chartControl.Series.Clear();
            InChart dbInChart = new InChart(dbStdQuery.StdQuery.InCharts);
            var ix = dbInChart.SciptObject.ToList()[Convert.ToInt32(Request.QueryString["_Chart"])];
            int VisibleItem = ix.Value.VisibleItem != null && ix.Value.VisibleItem.Length != 0 ?
                Convert.ToInt32(ix.Value.VisibleItem) : 10;

            var dtFilter = dtSource.SelectToDataTable(
                string.Format(dtSource.GetDataRowIndexFieldName() + " >= {0} and "
                + dtSource.GetDataRowIndexFieldName() + " < {1}",
                pageIndex * VisibleItem, (pageIndex + 1) * VisibleItem)
                );
            chartControl.BorderOptions.Visible = false;
            chartControl.Width = 900;
            chartControl.Height = 330;
            var Field_Y = ix.Value.Field_Y.Split(';').ToList();
            Field_Y.Remove("");

            if (dtFilter.Columns[ix.Value.Field_X].DataType.Name.IndexOf("DateTime") != -1)
            {
                if (!dtFilter.Columns.Contains(ix.Value.Field_X + "_N"))
                {
                    dtFilter.Columns.Add(new DataColumn() { DataType = Type.GetType("System.String"), ColumnName = ix.Value.Field_X + "_N" });
                    for (int i = 0; i < dtFilter.Rows.Count; i++)
                    {
                        dtFilter.Rows[i][ix.Value.Field_X + "_N"] = DateTime.Parse(dtFilter.Rows[i][ix.Value.Field_X].ToString()).ToString("yyyy-MM-dd");
                    }
                }
                ix.Value.Field_X += "_N";
            }
            //ix.Value.ChartType = "1";
            foreach (var f in Field_Y)
            {
                Series series = null;
                var seriesName = dtFilter.Columns[f].Caption;
                switch (ix.Value.ChartType)
                {
                    case "0":
                        series = new Series(seriesName, ViewType.Bar);
                        break;
                    case "1":
                        series = new Series(seriesName, ViewType.Point);
                        break;
                    case "2":
                        series = new Series(seriesName, ViewType.Line);
                        break;
                    case "3":
                        series = new Series(seriesName, ViewType.Area);
                        break;
                    case "4":
                        series = new Series(f, ViewType.Pie);
                        series.LegendText = f;
                        series.ShowInLegend = true;

                        series.PointOptions.PointView = PointView.ArgumentAndValues;
                        series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
                        //series.PointOptions.ValueNumericOptions.Precision = 0;

                        PieSeriesView myView = (PieSeriesView)series.View;
                        myView.HeightToWidthRatio = 90;
                        myView.Titles.Add(new SeriesTitle() { Text = f });
                        ((PieSeriesLabel)series.Label).Visible = false;

                        break;
                }

                //Series series = new Series(f, ViewType.Bar);
                //Series series = new Series(f, ViewType.Point);
                //Series series = new Series(f, ViewType.Area);
                //Series series = new Series(f, ViewType.Pie);
                //Series series = new Series(f, ViewType.StackedBar);
                series.DataSource = dtFilter;
                series.LegendPointOptions.ArgumentDateTimeOptions.FormatString = "yyyy-MM-dd";

                series.PointOptions.ArgumentDateTimeOptions.FormatString = "yyyy-MM-dd";
                series.ArgumentDataMember = ix.Value.Field_X;//X轴的数据字段
                series.ValueDataMembers[0] = f;//Y轴的数据字段
                chartControl.Series.Add(series);
                //chartControl.Width = 1024;
                //chartControl.Height = 900;
            }


            paper.ItemCount = dtSource.Rows.Count;
        }
    }
}